import React, { useState, useEffect, useRef } from 'react';
import { Resizable } from 'react-resizable'; //拖拽第三方库
import { Table, Modal, Form, Input } from 'antd';
import { CloseOutlined, InfoOutlined } from '@ant-design/icons';
import './style.less';
import axios from 'axios';
export default function Index() {
  // 拖拽
  const [dcolumns, setDcolumns] = useState([]);
  const [components, setComponents] = useState({});
  // 控制修改提示框
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 提示框的提示信息
  const [tips, setTips] = useState('请选择要修改的数据');
  // 控制修改弹出框显示与否
  const [editModal, setEditModal] = useState(false);
  // 添加form表单的ref
  const addFormRef = useRef();
  // 数据
  const [list, setList] = useState([]);
  // 存放将要修改的数据
  const [willEditData, setWillEditData] = useState();
  // 列
  const column = [
    {
      title: '序号',
      width: '7%',
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: '新闻标题',
      dataIndex: 'title',
      width: 600,
      ellipsis: true,
    },
    {
      title: '发布时间',
      dataIndex: 'datetime',
      width: 100,
      ellipsis: true,
    },
    {
      title: '创建人',
      dataIndex: 'createuser',
      width: 100,
      ellipsis: true,
    },
  ];
  useEffect(() => {
    a();
    getnews();
    setDcolumns(column),
      setComponents({
        header: {
          cell: ResizeableTitle,
        },
      });
  }, []);
  const a = async () => {
    let { data } = await axios.get('http://localhost:8081/list2');
    console.log(data);
  };

  // 拖拽
  const ResizeableTitle = (props) => {
    const { onResize, width = 100, ...restProps } = props;
    if (!width) {
      return <th {...restProps} />;
    }

    return (
      <Resizable width={width} height={0} onResize={onResize}>
        <th {...restProps} />
      </Resizable>
    );
  };
  const handleResize =
    (index) =>
    (e, { size }) => {
      // console.log('size', size);

      const nextColumns = [...columns];
      nextColumns[index] = {
        ...nextColumns[index],
        width: size.width,
      };
      setDcolumns(nextColumns);
    };
  const columns = dcolumns.map((col, index) => ({
    ...col,
    onHeaderCell: (column) => ({
      width: col.width * 1 || 100,
      onResize: handleResize(index),
    }),
  }));
  // 多选框回调
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      let item = selectedRows[0];
      setWillEditData(item);
    },
  };
  // 修改回调
  const upt = () => {
    if (!willEditData) {
      setTips('请选择要修改的数据!');
      return setIsModalOpen(true);
    }
    setEditModal(true);
  };
  // 点击左上角x号的回调
  const handleCancel = () => {
    // setAddModal(false);
    setEditModal(false);
    setIsModalOpen(false);
  };
  // 删除回调
  const del = () => {
    if (!willEditData) {
      setTips('请选择要删除的数据!');
      return setIsModalOpen(true);
    }
  };
  // 保存回调
  const preservation = () => {
    addFormRef.current.submit();
  };
  // 添加的form表单验证
  const onFinish = (values) => {
    console.log('Success:', values);
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const getnews = async () => {
    let { data } = await axios.get('http://127.0.0.1:7777/news/new');
    console.log(data);
    setList(data.newslist);
  };
  return (
    <div className="news">
      <div className="news_top system_management_top">
        <button>新增</button>
        <button onClick={upt}>修改</button>
        <button onClick={del}>删除</button>
        <span>名称：</span>
        <input type="text" />
        <button>查询</button>
        <button>查看日志</button>
      </div>
      <div className="news_table">
        <Table
          components={components}
          pagination={false}
          bordered
          rowSelection={{
            ...rowSelection,
          }}
          rowKey={(columns) => columns._id}
          columns={columns}
          dataSource={list}
        />
        {/* 修改对话框 */}
        <Modal
          destroyOnClose
          footer={false}
          title="全国省市"
          open={editModal}
          onCancel={handleCancel}
        >
          <div className="addModalTop system_management_top">
            <button onClick={preservation}>保存</button>
            <button>保存且更新</button>
            <button>草稿箱</button>
            <button>删除</button>
            <button>查看日志</button>
          </div>
          <div className="addModalForm">
            <div className="addModalForm_title system_body_title">
              <span>全国省市</span>
            </div>
            <Form
              ref={addFormRef}
              name="basic"
              labelCol={{
                span: 6,
              }}
              wrapperCol={{
                span: 16,
              }}
              initialValues={willEditData}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              autoComplete="off"
            >
              <Form.Item
                label="上级地区"
                name="par_city"
                rules={[
                  {
                    message: '不能为空!',
                  },
                ]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                label="地区编号"
                name="city_id"
                rules={[
                  {
                    required: true,
                    message: '不能为空!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="地区名称"
                name="city"
                rules={[
                  {
                    required: true,
                    message: '不能为空!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Form>
          </div>
        </Modal>
      </div>
      {/* 修改提示对话框 */}
      <div
        className="logininfo editModal"
        style={{ display: isModalOpen ? 'block' : 'none' }}
      >
        <div className="logininfotop">
          <p>提示对话框</p>
          <span className="logininfotopcha" onClick={handleCancel}>
            <CloseOutlined />
          </span>
        </div>
        <div className="logininfocenter">
          <span className="logininfocentertu">
            <InfoOutlined style={{ color: 'white' }} />
          </span>
          <p>{tips}</p>
        </div>
        <div className="logininfobottom tipsbottom">
          <button onClick={handleCancel}>确定</button>
        </div>
      </div>
      {/* 遮罩层 */}
      <div
        className="cover"
        style={{ display: isModalOpen ? 'block' : 'none' }}
      ></div>
    </div>
  );
}
